package leetcode_1_200;

public class LeeCode_91_2 {
    public static void main(String[] args) {
        System.out.println(numDecodings("230"));
    }
    private static int numDecodings(String s) {
        int len = s.length();
        if (len == 0){
            return 0;
        }
        if (len == 1){
            return s.charAt(0) == '0' ? 0 : 1;
        }
        int[] dp = new int[len];
        if (s.charAt(0) == '0'){
            return 0;
        }else {
            dp[0] = 1;
        }
        if (s.charAt(1) == '0'){
            if (s.charAt(0) > '2'){
                return 0;
            }else {
                dp[1] = 1;
            }
        }else {
            if (Integer.parseInt(s.charAt(0) + "" + s.charAt(1)) > 26){
                dp[1] = 1;
            }else {
                dp[1] = 2;
            }
        }
        for (int i = 2; i < len; i++) {
            if (s.charAt(i) == '0'){
                if (s.charAt(i - 1) == '0' || s.charAt(i - 1) > '2')
                    return 0;
                dp[i] = dp[i - 2];
            }else if (!(s.charAt(i - 1) == '1' || (s.charAt(i - 1) == '2' && s.charAt(i) <= '6'))){
                dp[i] = dp[i - 1];
            }else {
                dp[i] = dp[i - 2] + dp[i - 1];
            }
        }
        return dp[len - 1];
    }
}
